<template>
  <div class="addresses">
    <van-nav-bar
      title="修改订单"
      fixed
      @click-left="onClickLeft"
      @click-right="onClickRight"
    >
      <van-icon name="arrow-left" slot="left" color="#333" size="0.6rem" />
      <van-icon
        :name="require('@/assets/img/computer.png')"
        slot="right"
        color="#333"
        size="0.6rem"
      />
    </van-nav-bar>
    <div class="consignor">
      <van-cell-group>
        <van-field
          v-model="date.shrpPeopleName"
          label="发货人"
          input-align="right"
          :disabled="disabledshrpDes"
        />
        <van-field
          v-model="date.shrpPeopleTel"
          type="tel"
          label="联系方式"
          input-align="right"
          maxlength="11"
          :disabled="disabledshrpDes"
        />
        <van-cell
          title="发货地址"
          :is-link="!disabledshrp"
          :value="
            showadd
              ? ''
              : arryShrpList.province_list[date.shrpProvinceCode] +
                ' ' +
                arryShrpList.city_list[date.shrpCityCode] +
                ' ' +
                arryShrpList.county_list[date.shrpAreaCode]
          "
          @click="consignor('arryShrpList')"
        />
        <van-field
          v-model="date.shrpDes"
          type="tel"
          label="详细地址"
          input-align="right"
          maxlength="60"
          :disabled="disabledshrpDes"
        />
      </van-cell-group>

      <van-cell-group class="count">
        <van-cell class="total" :title="`经停点信息`">
          <template #right-icon>
            <span class="addStopOrder" @click="addStop">+添加经停</span>
          </template>
        </van-cell>
      </van-cell-group>

      <van-popup v-model="showadd" position="bottom">
        <van-area
          :area-list="arryShrpList"
          :value="shrparea"
          class="arryShrpList"
          @confirm="sendconfirm"
          @cancel="sendcancel"
          @change="changeArea"
        />
      </van-popup>
    </div>
    <div class="stopOver" v-for="(item, index) in stopOverList" :key="index">
      <van-cell-group>
        <van-cell class="total" :title="`经停点${stopOverList.length - index}`">
          <template #right-icon>
            <span class="addStopOrder" @click="removeStop(index)"
              >-删除经停</span
            >
          </template>
        </van-cell>
        <van-field
          v-model="item.shrpPeopleName"
          label="经停联系人"
          input-align="right"
          :disabled="disabledcneeDes"
        />
        <van-field
          v-model="item.shrpPeopleTel"
          type="tel"
          label="联系方式"
          maxlength="11"
          input-align="right"
          :disabled="disabledcneeDes"
        />
        <van-cell
          title="经停地址"
          :is-link="!disabledcnee"
          :value="`${item.shrpProvinceName} ${item.shrpCityName} ${item.shrpAreaName}`"
          @click="changeStopReceiveAdd(index)"
        />
        <van-field
          v-model="item.shrpDes"
          type="tel"
          label="经停详细地址"
          input-align="right"
          maxlength="60"
          :disabled="disabledcneeDes"
        />
        <van-cell
          title="货量"
          :value="
            item.kaGoodTypeSumInfo
              ? item.kaGoodTypeSumInfo.kaWeightKg == ''
                ? '请填写'
                : `${item.kaGoodTypeSumInfo.kaQuantity}件-${item.kaGoodTypeSumInfo.kaWeightKg}kg-${item.kaGoodTypeSumInfo.kaVolume}m³`
              : '请填写'
          "
          @click="goodsclick(index)"
        />
      </van-cell-group>
    </div>
    <van-popup v-model="stopOverflag" position="bottom">
      <van-area
        :area-list="arryReceiveList"
        :value="stoparea"
        class="arryReceiveList"
        @confirm="stopreceiveconfirm"
        @cancel="stopreceivecancel"
        @change="stopchangeArea"
      />
    </van-popup>
    <div class="receive">
      <van-cell-group>
        <van-field
          v-model="date.cneePeopleName"
          label="收货人"
          input-align="right"
          :disabled="disabledcneeDes"
        />
        <van-field
          v-model="date.cneePeopleTel"
          type="tel"
          label="联系方式"
          maxlength="11"
          input-align="right"
          :disabled="disabledcneeDes"
        />
        <van-cell
          title="收货地址"
          :is-link="!disabledcnee"
          :value="
            showReceiveAdd || !arryReceiveList.county_list[date.cneeAreaCode]
              ? ''
              : (arryReceiveList.province_list[date.cneeProvinceCode] +
                ' ' +
                arryReceiveList.city_list[date.cneeCityCode] +
                ' ' +
                arryReceiveList.county_list[date.cneeAreaCode])
          "
          @click="changeReceiveAdd('arryReceiveList')"
        />
        <van-field
          v-model="date.cneeDes"
          type="tel"
          label="详细地址"
          input-align="right"
          maxlength="60"
          :disabled="disabledcneeDes"
        />
      </van-cell-group>
      <van-popup v-model="showReceiveAdd" position="bottom">
        <van-area
          :area-list="arryReceiveList"
          :value="cneearea"
          class="arryReceiveList"
          @confirm="receiveconfirm"
          @cancel="receivecancel"
          @change="changeArea"
        />
      </van-popup>
    </div>
    <!-- <div class='message'>
      <van-field v-model="date.modifyRemark"
                 label="修改备注"
                 rows="1"
                 autosize
                 type="textarea"
                 show-word-limit
                 class='field'
                 required
                 maxlength="50" />
    </div> -->
    <div class="footer">
      <div class="btn-wrap">
        <div class="btn-left" @click="handelCancel">
          <span>取消</span>
        </div>
        <div class="btn-right" @click="handelSave">
          <span>保存</span>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Vue from "vue";
import { AddressEdit } from "vant";
import { Popup } from "vant";
import AreaList from "../../../utils/area.js";
Vue.use(AddressEdit);
Vue.use(Popup);
import { Area } from "vant";
Vue.use(Area);
import { orderSelect, orderChange } from "@/api/order";
import { getKaUserInfo, cities, areas } from "@/api/add";
export default {
  data() {
    return {
      sendDetail: "",
      sendUser: "",
      sendPhone: "",
      arryShrpList: JSON.parse(JSON.stringify(AreaList)),
      arryReceiveList: JSON.parse(JSON.stringify(AreaList)),
      selectedAddItem: "arryShrpList",
      showadd: false,
      sendadd: "",
      receiveUser: "",
      receivePhone: "",
      receiveAddress: "",
      receiveDetail: "",
      showReceiveAdd: false,
      message: "",
      stopOverList: [],
      stopOverflag: false,
      stopind: 0,
      shrparea: "110101",
      stoparea: "110101",
      cneearea: "110101",
      date: {
        // modifyRemark: ''
      },
    };
  },
  mounted() {
    this.orderId = this.$route.query.orderId;
    if (this.orderId) {
      this.getData();
    }
  },
  methods: {
    getData() {
      orderSelect(this.orderId).then((res) => {
        this.date = res.data;
        if (JSON.parse(sessionStorage.getItem("stopOverList"))) {
          this.stopOverList = JSON.parse(
            sessionStorage.getItem("stopOverList")
          );
        } else {
          
          this.stopOverList = res.data.stopOverList.reverse();
          sessionStorage.setItem(
            "stopOverList",
            JSON.stringify(this.stopOverList)
          );
        }
        let sendProvince = this.arrylist.province_list[
          this.date.shrpProvinceCode
        ];

        let sendCity = this.arrylist.city_list[this.date.shrpCityCode];

        console.log(sendCity, this.date.shrpCityCode, "sendCity");

        let sendCounty = this.arrylist.county_list[this.date.shrpAreaCode];

        let receiveProvince = this.arrylist.province_list[
          this.date.cneeProvinceCode
        ];

        let receiveCity = this.arrylist.city_list[this.date.cneeCityCode];

        console.log(this.arrylist, this.date.cneeCityCode, "receiveCity");

        let receiveCounty = this.arrylist.county_list[this.date.cneeAreaCode];

        // this.sendUser = this.date.shrpPeopleName;
        // this.sendPhone = this.date.shrpPeopleTel;
        // this.sendDetail = this.date.shrpDes;
        this.sendadd = sendProvince + sendCity + sendCounty;

        // this.receiveUser = this.date.cneePeopleName;
        // this.receivePhone = this.date.cneePeopleTel;
        // this.receiveDetail = this.date.cneeDes;
        this.receiveAddress = receiveProvince + receiveCity + receiveCounty;

        this.kaUserInfo(this.date.kaUserId);
        // this.getcities(this.date.cneeProvinceCode);
        // this.getareas(this.date.cneeCityCode);

        // if (this.date.modifyRemark === null) {
        //   this.date.modifyRemark = '';
        // }
      });
    },
    kaUserInfo(userId) {
      getKaUserInfo(userId).then((res) => {
        console.log(res);
      });
    },
    goodsclick(index) {
      sessionStorage.setItem("stopOverList", JSON.stringify(this.stopOverList));
      this.$router.push(`/stopgoods?ind=${index}`);
    },
    addStop() {
      this.stopOverList.unshift({
        kaGoodsTypeList: [
          {
            KaGoodName: "",
            KaQuantity: "",
            KaWeightKg: "",
            KaVolume: "",
            kaLong: "",
            kaWidth: "",
            kaHigh: "",
            KaGoodPackage: 0,
            Fragile: 0,
            Pressurable: 0,
            goodSituation: 0,
            kaAlien: "",
          },
        ],
        kaGoodTypeSumInfo: {
          dataSum: "", //总计
          kaQuantity: "", //件数
          kaVolume: "", // 体积
          kaWeightKg: "", // 重量
        },
        shrpPeopleName: "",
        shrpPeopleTel: "",
        shrpProvinceCode: "110000000000",
        shrpProvinceName: "北京市",
        shrpCityCode: "110100000000",
        shrpCityName: "北京市",
        shrpAreaCode: "110101000000",
        shrpAreaName: "东城区",
        shrpDes: "",
        kaUserId: "",
      });
      sessionStorage.setItem("stopOverList", JSON.stringify(this.stopOverList));
    },
    removeStop(ind) {
      this.stopOverList.splice(ind, 1)
      sessionStorage.setItem("stopOverList", JSON.stringify(this.stopOverList));
    },
    getcities(code) {
      cities(code).then((res) => {
        let that = this;

        // debugger;
        let cityList = that[that.selectedAddItem].city_list;

        //将获取到的城市 格式化成{110000000000:北京}的格式
        if (res.code == 200) {
          cityList = {};
          res.data.forEach((item) => {
            cityList[item.AreaId] = item.AreaName;
          });
          that.getareas(res.data[0].AreaId);
        }

        that[that.selectedAddItem]["city_list"] = cityList;
      });
    },
    getareas(code) {
      areas(code).then((res) => {
        let that = this;

        let countyList = that[that.selectedAddItem].county_list;

        //将获取到的城市 格式化成{110000000000:北京}的格式
        if (res.code == 200) {
          countyList = {};
          res.data.forEach((item) => {
            countyList[item.AreaId] = item.AreaName;
          });
        }

        that[that.selectedAddItem]["county_list"] = countyList;
      });
    },
    onClickLeft() {
      this.$router.back();
    },
    onClickRight() {
      let url = window.location.host;

      let index = url.indexOf("pre");

      if (index <= -1) {
        window.location.href = "https://ka.lecarlink.com/index.aspx";
      } else {
        window.location.href = "https://ka-pre.lecarlink.com/index.aspx";
      }
    },
    consignor(item) {
      this.selectedAddItem = item;
      console.log(item);
      this.shrparea = this.date.shrpAreaCode
        ? String(this.date.shrpAreaCode)
        : "110101";
      if (this.disabledshrp) {
        return;
      }
      this.showadd = true;
    },
    changeStopReceiveAdd(ind) {
      this.stopOverflag = true;
      this.stoparea = this.stopOverList[ind].shrpAreaCode
        ? String(this.stopOverList[ind].shrpAreaCode)
        : "110101";
      this.stopind = ind;
    },
    sendconfirm(e) {
      console.log(e);
      this.showadd = false;
      this.regiondata = e;
      // this.sendadd = this.regiondata[0].name + this.regiondata[1].name + this.regiondata[2].name
      this.date.shrpProvinceCode = this.regiondata[0].code;
      this.date.shrpCityCode = this.regiondata[1].code;
      this.date.shrpAreaCode = this.regiondata[2].code;
      console.log(this.date)
    },
    //点击收货人的地址
    changeReceiveAdd(item) {
      this.selectedAddItem = item;
      this.cneearea = this.date.cneeAreaCode
        ? String(this.date.cneeAreaCode)
        : "110101";
      if (this.disabledcnee) {
        return;
      }
      this.showReceiveAdd = true;
    },
    stopreceiveconfirm(val) {
      console.log(val);
      console.log(this.stopind);
      this.stopOverList[this.stopind].shrpProvinceCode = val[0].code;
      this.stopOverList[this.stopind].shrpCityCode = val[1].code;
      this.stopOverList[this.stopind].shrpAreaCode = val[2].code;
      this.stopOverList[this.stopind].shrpProvinceName = val[0].name;
      this.stopOverList[this.stopind].shrpCityName = val[1].name;
      this.stopOverList[this.stopind].shrpAreaName = val[2].name;
      console.log(this.stopOverList);
      sessionStorage.setItem("stopOverList", JSON.stringify(this.stopOverList));
      this.stopOverflag = false;
    },
    stopreceivecancel() {
      this.stopOverflag = false;
    },
    stopchangeArea() {},
    receiveconfirm(val) {
      this.showReceiveAdd = false;
      this.receive = val;
      this.date.cneeProvinceCode = this.receive[0].code;
      this.date.cneeCityCode = this.receive[1].code;
      this.date.cneeAreaCode = this.receive[2].code;
      this.receiveAddress =
        this.receive[0].name + this.receive[1].name + this.receive[2].name;
    },
    sendcancel() {
      this.arryShrpList = JSON.parse(JSON.stringify(AreaList));
      this.showadd = false;
    },
    receivecancel() {
      this.arryReceiveList = JSON.parse(JSON.stringify(AreaList));
      this.showReceiveAdd = false;
    },
    handelCancel() {
      console.log("handelCancel");
      this.$router.back();
    },
    handelSave() {
      if (this.date.orderStatusBack >= 13) {
        this.$toast.fail("该订单状态不能修改地址信息");
        return;
      }
      if (this.date.modifyStatus == 1) {
        this.$toast.fail("该订单已在审核修改中");
        return;
      }
      if (this.validate()) {
        this.date.kaOrderId = this.orderId;
        this.date.isAbnomal = 0;
        this.date.carrierFlag = 0; // 确认承运的标识
        this.date.stopOverList = this.stopOverList.reverse();
        // this.date.peoplePrice = (Number(this.date.ganXianPrice) + Number(this.date.faHuoPrice) + Number(this.date.tiHuoPrice)).toFixed(2);
        this.date.userContractId =  this.$router.history.current.query.userContractId
        this.date.shrpProvinceName = this.arryShrpList.province_list[this.date.shrpProvinceCode]
        this.date.shrpCityName = this.arryShrpList.city_list[this.date.shrpCityCode]
        this.date.shrpAreaName = this.arryShrpList.county_list[this.date.shrpAreaCode]
        this.date.cneeProvinceName = this.arryReceiveList.province_list[this.date.cneeProvinceCode]
        this.date.cneeCityName = this.arryReceiveList.city_list[this.date.cneeCityCode]
        this.date.cneeAreaName = this.arryReceiveList.county_list[this.date.cneeAreaCode]
        this.date.kaShprAddressbookId = ""
        this.date.kaCneeAddressbookId = ""

        orderChange(this.date).then((res) => {
          if (res.code == 200) {
            sessionStorage.removeItem("stopOverList");
            this.$router.back();
          }
        });

         if(this.date.modifyRemark.trim()!="") {
            orderChange(this.date).then(res => {
          if (res.code == 200) {
            this.$router.back();
          }
        });
         } else {
            this.date.modifyRemark = "";
            this.$toast.fail("请填写修改订单备注");
         }

        console.dir(JSON.stringify(this.date, null, 2));
      }
    },
    validate() {
      let msg = "";
      var shrpPeopleName = this.date.shrpPeopleName;
      var shrpPeopleTel = this.date.shrpPeopleTel;
      var shrpDes = this.date.shrpDes;
      var regPhone = /^1(3|4|5|6|7|8|9)\d{9}$/;

      var cneePeopleName = this.date.cneePeopleName;
      var cneePeopleTel = this.date.cneePeopleTel;
      var cneeDes = this.date.cneeDes;

      if (!shrpPeopleName) {
        msg += "请填写发货人\n";
        this.$toast.fail(msg);
        return false;
      } else if (!shrpPeopleTel) {
        msg += "请填写发货人的联系电话\n";
        this.$toast.fail(msg);
        return false;
      } else if (!regPhone.test(shrpPeopleTel)) {
        msg += "请填写正确的发货人联系电话\n";
        this.$toast.fail(msg);
        return false;
      } else if (!shrpDes) {
        msg += "请填写发货详细地址\n";
        this.$toast.fail(msg);
        return false;
      } else if (!cneePeopleName) {
        msg += "请填写收货人\n";
        this.$toast.fail(msg);
        return false;
      } else if (!cneePeopleTel) {
        msg += "请填写收货人的联系电话\n";
        this.$toast.fail(msg);
        return false;
      } else if (!regPhone.test(cneePeopleTel)) {
        msg += "请填写正确收货人的联系电话\n";
        this.$toast.fail(msg);
        return false;
      } else if (!cneeDes) {
        msg += "请填写收货详细地址\n";
        this.$toast.fail(msg);
        return false;
      }
      //  else if (!this.date.modifyRemark) {
      //   msg += '请填写修改订单备注\n';
      //   this.$toast.fail(msg);
      //   return false;
      // }
      return true;
    },
    changeArea(picker, index, value) {
      console.log(picker);
      console.log(index);
      console.log(value);
      // console.log(item);
      if (value == 0) {
        this.getcities(index[0].code);
      } else if (value == 1) {
        this.getareas(index[1].code);
      }
    },
  },
  computed: {
    //0待提货 1-已提货 2-已承运 3-待承运 4-出运 7-到达站点 10派送中 13-签收(妥投) 14 异常签收  15 拒签 18回执已取
    disabledshrpDes() {
      // 如果是(已承运、已出运、已到站、已签收)--不能修修改发货详细地址
      return [1, 2, 3, 4, 7, 10, 13, 14, 15, 18].includes(
        this.date.orderStatusBack
      );
    },
    disabledcneeDes() {
      // 如果是(10派送中 13-签收(妥投) 14 异常签收  15 拒签 18回执已取)--不能修修改收货详细地址
      return [10, 13, 14, 15, 18].includes(this.date.orderStatusBack);
    },
    disabledshrp() {
      return [0, 1, 2, 3, 4, 7, 10, 13, 14, 15, 18].includes(
        this.date.orderStatusBack
      );
    },
    disabledcnee() {
      return [2, 4, 7, 10, 13, 14, 15, 18].includes(this.date.orderStatusBack);
    },
  },
};
</script>
<style lang='scss'>
.addresses {
  padding: 0 0 70px 0;
  box-sizing: border-box;
}
.consignor {
  padding-top: 55px;
  text-align: left;
  margin: 0 15px;
  /deep/ .van-picker__cancel,
  .van-picker__confirm {
    color: #f18d00;
  }
  /deep/.van-picker-column__wrapper li {
    height: 44px; /*no*/
  }
}

.receive,
.stopOver {
  padding-top: 10px;
  text-align: left;
  margin: 0 15px;
  /deep/ .van-picker__cancel,
  .van-picker__confirm {
    color: #f18d00;
  }
}

.message {
  padding-top: 10px;
  margin: 0 15px;
}

.footer {
  background: #fff;
  text-align: center;
  position: fixed;
  bottom: 0;
  right: 0;
  left: 0;
  .btn-wrap {
    padding: 10px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .btn-left {
      background: #fdf3e4;
      border: 1px solid #f18d00;
      border-radius: 2px;
      color: #f18d00;
      font-size: 18px;
      width: 47%;
      height: 44px;
      line-height: 44px;
      box-sizing: border-box;
    }
    .btn-right {
      width: 47%;
      height: 44px;
      line-height: 44px;
      font-size: 18px;
      background: #f18d00;
      border: 1px solid #f18d00;
      box-sizing: border-box;
      border-radius: 2px;
      color: #fff;
    }
  }
}
.addStopOrder {
  color: #f18d00;
  font-weight: bold;
  font-size: 13px;
}
</style>


